﻿/*-------------------------------------
//
//Copyright (C) 2007 开发二组 版权所有。
//
//文件名：ProductAdd.ascx.cs
//
//文件功能描述：商品添加和修改
// 
//创建标识：2007.11.22 施欢
//创建描述：创建页面逻辑代码
//
//修改标识：2007.11.30 施欢
//修改描述：按编码规范修改了代码，增加了添加多幅图片的功能
------------------------------------*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

/// <summary>
/// 商品添加或修改(管理)
/// </summary>
public partial class UserControls_ProductAdd : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //初次加载页面时初始化页面
        if (!Page.IsPostBack)  
        {
            localhost.ProductService service = new localhost.ProductService();

            //用于保存大类别的初始选项
            string upperCategoryID = string.Empty; 

            //获取大类别列表
            GetUpperCategoryList();   
            
            //获取大类别的初始选项
            upperCategoryID = dropUpperCategory.SelectedValue.ToString();
            
            //获取初始大类别下对应的小类别列表
            GetLowerCategotyListByUpperCategoryID(upperCategoryID);

            //获取计量单位列表
            GetUnitList();           
            gdvImage.Visible = false; //在添加商品状态下,图片列表不可见
            lblMsg.Visible = false;   //提示信息不可见
            
            //如果是修改商品信息,要添充其他的控件
            if (Request.QueryString["ProductID"] != null)
            {
                lnkOrderManage.Text = "商品修改";
                
                //获取要修改的商品编号
                string strProdctID = Request.QueryString["ProductID"].ToString();
                localhost.Product productModel = new localhost.Product();
                productModel = service.GetProductModelByID(strProdctID);
                string strLowerCategoryID = productModel.LowerCategoryID;
                string strUnitID = productModel.UnitID.ToString();
                
                //显示商品对应的小类别名称
                SelectNameByID(strLowerCategoryID, dropLowerCatagory);

                //显示商品对应的计量单位名称
                SelectNameByID(strUnitID, dropUnits); 
                txtProductName.Text = productModel.Name; 
                localhost.LowerCategory lowerCategotyModel = service.GetLowerCategoryModel(strLowerCategoryID);
                string strUpperCategoryID = lowerCategotyModel.UpperCategoryID;

                //显示商品对应的大类别名称
                SelectNameByID(strUpperCategoryID, dropUpperCategory); 
                txtSalesPrice.Text = productModel.SalesPrice.ToString();
                if (productModel.Status == true)
                {
                    dropStatus.SelectedIndex = 0;
                }
                else
                {
                    dropStatus.SelectedIndex = 1;
                }
                chkRecommendation.Checked = productModel.Recommendation;
                FreeTextBox1.Text = productModel.Description;
                gdvImage.Visible = true;  //显示商品的所有图片列表
                lblMsg.Visible = true;    //显示提示信息
                GetImageList(strProdctID);

            }
        }
    }
    
    /// <summary>
    /// 获取商品大类别列表并绑定到大类别控件
    /// </summary>
    private void GetUpperCategoryList()
    {
        localhost.ProductService service = new localhost.ProductService();
        DataSet dsUpperCategoryList = service.GetUpperCategoryList();
        dropUpperCategory.DataSource = dsUpperCategoryList.Tables[0];
        dropUpperCategory.DataTextField = "Name";
        dropUpperCategory.DataValueField = "UpperCategoryID";
        dropUpperCategory.DataBind();
    }
   
    /// <summary>
    /// 异步调用方法获取商品的所有图片列表
    /// </summary>
    /// <param name="strProductID">商品编号</param>
    private void GetImageList(string strProductID)
    {
        localhost.ProductService service = new localhost.ProductService();
        service.GetProductImageListByProductIDCompleted+=new localhost.GetProductImageListByProductIDCompletedEventHandler(service_GetProductImageListByProductIDCompleted);
        service.GetProductImageListByProductIDAsync(10,1,strProductID);
    }

    /// <summary>
    /// 获取商品所有图片列表的回调函数
    /// </summary>
    /// <param name="sender">发送该事件的对象</param>
    /// <param name="e">网页事件的基本参数</param>
    private void service_GetProductImageListByProductIDCompleted(object sender,localhost.GetProductImageListByProductIDCompletedEventArgs e)
    {
        DataSet dsImageList = e.Result;
        gdvImage.DataSource = dsImageList;
        gdvImage.DataBind();

    }

    /// <summary>
    /// 根据编号在dropDrowList控件中显示编号对应的名字
    /// </summary>
    /// <param name="strID">编号</param>
    /// <param name="dropList">dropDownList控件</param>
    private void SelectNameByID(string strID, DropDownList dropList)
    {
        //循环遍历dropDrowList控件
        for (int i = 0; i < dropList.Items.Count; i++)
        {
            if (dropList.Items[i].Value == strID)  //找到对应的项时显示该项     
            {
                dropList.SelectedIndex = i;
                break;
            }
        }
    }

    /// <summary>
    /// 根据大类别编号获取该大类别下的所有小类别列表
    /// </summary>
    /// <param name="strUpperCategoryID">大类别编号</param>
    private void GetLowerCategotyListByUpperCategoryID(string strUpperCategoryID)
    {
        localhost.ProductService service = new localhost.ProductService();
        
        //获取大类别下的所有小类别列表
        DataSet dsLowerCategoryList = service.GetLowCategoryListByUpperCategoryID(strUpperCategoryID);
        dropLowerCatagory.DataSource = dsLowerCategoryList.Tables[0];
        dropLowerCatagory.DataTextField = "Name";
        dropLowerCatagory.DataValueField = "LowerCategoryID";
        dropLowerCatagory.DataBind();
    }
    
    /// <summary>
    /// 获取计量单位列表并绑定到计量单位控件
    /// </summary>
    private void GetUnitList()
    {
        localhost.ProductService service = new localhost.ProductService();
        DataSet dsUnits = service.GetUnit();
        dropUnits.DataSource=dsUnits.Tables[0];
        dropUnits.DataTextField = "Name";
        dropUnits.DataValueField = "UnitID";
        dropUnits.DataBind();
    }

    /// <summary>
    /// 上传商品主图片(格式必须为.gif 或.jpg)
    /// </summary>
    /// <returns>成功时返回上传的图片数组,失败时返回空数组</returns>
    private byte[] UploadMainImage( )
    {
        byte[] bytImage = null;
        try
        {
            if (fulMaxPicture.HasFile) //FileUpload控件有图片要上传
            {
                int fileLen = fulMaxPicture.PostedFile.ContentLength;
                bytImage = new byte[fileLen];
                Stream stream = fulMaxPicture.PostedFile.InputStream;
                stream.Read(bytImage, 0, fileLen);  //保存上传的图片到数组中
            }
        }
        catch (Exception error)
        {
            lblImageMsg.Text = error.Message;
            lblImageMsg.Visible = true;
            bytImage = null;
        }

        return bytImage; //返回上传商品图片结果
    }

    /// <summary>
    /// 添加商品信息和商品主图片
    /// </summary>
    /// <returns>添加成功时返回新添加的商品编号，失败时返回空编号</returns>
    private string AddProduct()
    {
        string strPruductID = string.Empty;       //商品编号
        byte[] bytMainImage = UploadMainImage();  //用于保存商品主图片
        

        //商品主图片不为空时才可以添加商品
        if (bytMainImage != null)
        {
            lblImageMsg.Visible = false;  //设置错误信息提示不可见
            lblImageMsg2.Visible = false;
            localhost.Product productModel = new localhost.Product();

            //获取要添加的商品信息
            productModel.Name = txtProductName.Text.Trim();
            productModel.LowerCategoryID = dropLowerCatagory.SelectedValue.ToString();
            productModel.UnitID = Convert.ToInt32(dropUnits.SelectedValue.ToString());
            productModel.SalesPrice = Convert.ToDecimal(txtSalesPrice.Text.Trim());

            if (dropStatus.SelectedValue.ToString() == "1")
            {
                productModel.Status = true;
            }
            else
            {
                productModel.Status = false;
            }
            productModel.Recommendation = chkRecommendation.Checked;
            productModel.Description = FreeTextBox1.Text.Trim();
            productModel.CreationTime = DateTime.Now;
            localhost.ProductService service = new localhost.ProductService();
            strPruductID = service.AddProduct(productModel, bytMainImage);//添加商品
        }
        else
        {
            lblImageMsg2.Text = "商品主图片不能为空!";
            lblImageMsg2.Visible = true;
        }

        return strPruductID;
    }

    /// <summary>
    /// 修改商品信息
    /// </summary>
    /// <param name="strProductID">商品编号</param>
    /// <returns>成功时返回true,失败时返回false</returns>
    private bool UpdateProduct(string strProductID)
    {
        bool blnUpdateResult = false;  //修改操作结果
        bool blnUpdateImage = false;   //是否修改商品主图片
        byte[] bytMainImage = UploadMainImage(); //保存商品主图片
        if (bytMainImage != null)
        {
            blnUpdateImage = true;  //上传了主图片,说明要修改主图片
        }
        localhost.Product productModel = new localhost.Product();

        //获取商品的新信息
        productModel.ProductID = strProductID;
        productModel.Name = txtProductName.Text.Trim();
        productModel.LowerCategoryID = dropLowerCatagory.SelectedValue.ToString();
        productModel.UnitID = Convert.ToInt32(dropUnits.SelectedValue);
        productModel.SalesPrice = Convert.ToDecimal(txtSalesPrice.Text.Trim());

        if (dropStatus.SelectedValue.ToString() == "1")
        {
            productModel.Status = true;
        }
        else
        {
            productModel.Status = false;
        }
        productModel.Recommendation = chkRecommendation.Checked;
        productModel.Description = FreeTextBox1.Text.Trim();
        productModel.CreationTime = DateTime.Now; //(时间是否要修改有待改进)
        localhost.ProductService service = new localhost.ProductService();

        blnUpdateResult = service.ManageProduct(productModel);//修改商品信息(不含图片)
        if (blnUpdateResult && blnUpdateImage) //商品主图片也要修改
        {
            //获取商品的主图片编号
            DataSet ds = service.GetProductImageListByProductID(1, 1, strProductID);
            int imageID = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            blnUpdateResult = service.UpdateProductImage(imageID, strProductID, bytMainImage);//修改商品主图片
        }

        return blnUpdateResult;  //返回修改操作结果
    }

    /// <summary>
    /// 判断要添加的商品图片是否符合要求
    /// </summary>
    /// <returns>全部符合要求返回true，不符合要求返回false</returns>
    private bool ImageIsRight()
    {
        bool blnResult = true;    //图片是否符合要求
        lblMoreImageMsg.Visible = false;
        StringBuilder strMsg = new StringBuilder(string.Empty);  //存放错误信息
        HttpFileCollection files = HttpContext.Current.Request.Files;
        int fileNumber = files.Count;

        //依次遍历判断图片是否符合要求
        for (int i = 0; i < fileNumber; i++)
        {
            //相应的控件有图片要上传
            if (files[i].FileName.Length > 0)
            {
                HttpPostedFile postFile = files[i];
                string imgExtend = (Path.GetExtension(postFile.FileName)).ToLower();

                //判断图片扩展名是否符合要求
                if (!(imgExtend == ".jpg" || imgExtend == ".gif"))
                {
                    strMsg.Append(Path.GetFileName(postFile.FileName) + " 图片格式不对 ");
                    blnResult = false;
                    break;
                }

                //判断图片的大小是否符合要求(最大为1M)
                if (postFile.ContentLength / 1024 >1024)
                {
                    strMsg.Append(Path.GetFileName(postFile.FileName) + "图片长度不对");
                    blnResult = false;
                    break;
                }
            }
        }

        //图片不符合要求显示错误信息
        if (strMsg.Length > 0)
        {
            lblMoreImageMsg.Text = strMsg.ToString();
            lblMoreImageMsg.Visible = true;
            blnResult = false;
        }
       
        return blnResult;
    }

    /// <summary>
    /// 添加更多商品图片
    /// </summary>
    /// <param name="strProductID">商品编号</param>
    /// <returns>成功时返回true，失败时返回false</returns>
    private bool AddMoreImage(string strProductID)
    {
        bool blnResult = true;
        localhost.ProductService service = new localhost.ProductService();

        HttpFileCollection files = HttpContext.Current.Request.Files;

        //循环遍历添加商品的更多图片
        for (int i = 1; i < files.Count; i++)
        {
            if (blnResult == false)
            {
                break;
            }
            try
            {
                //相应的控件有图片要上传
                if (files[i].FileName.Length > 0)
                {
                    int fileLength = files[i].ContentLength;
                    byte[] bytMoreImage = new byte[fileLength];
                    Stream stream = files[i].InputStream;
                    stream.Read(bytMoreImage, 0, fileLength);
                    blnResult = service.AddProductImage(strProductID, bytMoreImage);

                }
            }
            catch (Exception error)
            {
                blnResult = false;

            }
        }

        return blnResult;  //返回添加商品多图的结果
    }

    
    //确定添加商品或修改商品信息
    protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        bool blnResult = false;             //商品添加或修改操作结果,成功时为true,失败时为false
        bool blnUpdateProduct = false;      //是否要修改商品信息
        string strPruductID = string.Empty; //商品编号
        bool blnImageIsRight = false;       //商品图片是否符合要求
         
        if (Request.QueryString["ProductID"] != null) //该页面处于修改商品信息状态
        {
            strPruductID = Request.QueryString["ProductID"].ToString();//取得要修改的商品编号
            blnUpdateProduct = true;
        }

        blnImageIsRight = ImageIsRight(); //判断商品图片是否符合要求

        if (blnImageIsRight)
        {
            //页面处于添加商品状态时实行的操作
            if (Page.IsValid && (!blnUpdateProduct))
            {

                strPruductID = AddProduct();
                if (strPruductID != string.Empty)
                {
                    blnResult = AddMoreImage(strPruductID);
                }
                if (blnResult == false)
                {
                    Page.RegisterStartupScript("warnings", "<script>alert('添加商品失败!');</script>");
                }
                else
                {
                    Page.RegisterStartupScript("warnings", "<script>alert('添加商品成功!');</script>");
                    
                    //清空输入框
                    txtProductName.Text = string.Empty;
                    txtSalesPrice.Text = string.Empty;
                    FreeTextBox1.Text = string.Empty;

                }

            }
            //修改商品信息时实行的操作
            if (Page.IsValid && blnUpdateProduct)
            {

                blnResult = UpdateProduct(strPruductID);
                if (blnResult)
                {
                    blnResult = AddMoreImage(strPruductID);
                }
                if (blnResult == false)
                {
                    Page.RegisterStartupScript("warnings", "<script>alert('修改商品信息失败！');</script>");
                }
                else
                {
                    Page.RegisterStartupScript("warnings", "<script>alert('修改商品信息成功!');</script>");
                    GetImageList(strPruductID);
                }
            }

        }
        
    }

    /// <summary>
    /// 如果大类别改变了,根据大类别编号获取该类别下的所有小类别列表
    /// </summary>
    /// <param name="sender">发送该事件的对象</param>
    /// <param name="e">网页事件的基本参数</param>
    protected void dropUpperCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strUpperCategoryID = dropUpperCategory.SelectedValue;
        GetLowerCategotyListByUpperCategoryID(strUpperCategoryID);
    }
    
    /// <summary>
    /// 取消操作
    /// </summary>
    /// <param name="sender">发送该事件的对象</param>
    /// <param name="e">网页事件的基本参数</param>
    protected void ibtnCancel_Click(object sender, ImageClickEventArgs e)
    {
        if (Request.QueryString["ProductID"] == null)
        {
            //添加商品时重定向到添加商品页面
            Server.Transfer("~/StoreKeeper/ProductAdd.aspx");
        }
        else
        {
            //修改商品时重定向到商品管理页面
            Server.Transfer("~/StoreKeeper/ProductManage.aspx");
        }
    }

    /// <summary>
    /// 删除商品图片,当商品只有一张图片时不能删除
    /// </summary>
    /// <param name="sender">发送该事件的对象</param>
    /// <param name="e">网页事件的基本参数</param>
    protected void gdvImage_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       
        bool blnResult = false;
        string strProductID = Request.QueryString["ProductID"].ToString();
        lblDeleteMsg.Visible = false;
        localhost.ProductService deleteImage = new localhost.ProductService();
        int imageID = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "DeleteImage")
        {
            //如果商品图片只有一张,不能删除
            if (gdvImage.Rows.Count == 1)
            {
                lblDeleteMsg.Text = "商品至少要有一张图片,不能删除!";
                lblDeleteMsg.Visible = true;
            }
            
            //图片多于一张时可以删除,编号最小的图片将成为主图片
            else
            {
                blnResult = deleteImage.DeleteProductImage(imageID);

                if (blnResult == true)
                {
                    //重新获取商品图片列表
                    GetImageList(strProductID); 
                }
                else
                {
                    lblDeleteMsg.Text = "删除商品图片失败!";
                    lblDeleteMsg.Visible = true;
                }
            }
        }

    }
}
